#!/bin/sh
#
# see: dh_installdeb(1)

set -e

package="c9-core-installer"

npm_install () {
	if [ -d /etc/avahi/ ] ; then
		#Annouce http server via DNS Sevice Discovery
		wfile="/etc/avahi/services/cloud9.service"
		echo "<?xml version=\"1.0\" standalone='no'?><!--*-nxml-*-->" > ${wfile}
		echo "<!DOCTYPE service-group SYSTEM \"avahi-service.dtd\">" >> ${wfile}
		echo "" >> ${wfile}
		echo "<!-- See avahi.service(5) for more information about this configuration file -->" >> ${wfile}
		echo "" >> ${wfile}
		echo "<service-group>" >> ${wfile}
		echo "" >> ${wfile}
		echo "  <name replace-wildcards=\"yes\">Cloud9 IDE for %h</name>" >> ${wfile}
		echo "  <service>" >> ${wfile}
		echo "" >> ${wfile}
		echo "    <type>_http._tcp</type>" >> ${wfile}
		echo "    <port>3000</port>" >> ${wfile}
		echo "  </service>" >> ${wfile}
		echo "" >> ${wfile}
		echo "</service-group>" >> ${wfile}
	fi
}

c9_directory () {

	if [ ! -d /var/lib/cloud9 ] ; then
		mkdir -p /var/lib/cloud9 || true
	fi

	if [ ! -d /opt/cloud9/.c9/node/bin/ ] ; then
		mkdir -p /opt/cloud9/.c9/node/bin/ || true
	fi
	ln -sf /opt/cloud9_support/bin/node /opt/cloud9/.c9/node/bin/node

	chown -R 1000:1000 /opt/cloud9/.c9/ || true
	chmod -R g+w /opt/cloud9/.c9/ || true

	mkdir -p /opt/cloud9/.cache/ || true
	chown -R 1000:1000  /opt/cloud9/.cache/ || true
	chmod -R g+w /opt/cloud9/.cache/ || true

	chown -R 1000:1000 /opt/cloud9/build/

	systemctl daemon-reload || true
	systemctl enable cloud9.socket || true
	systemctl restart cloud9.socket || true
	echo "${package}:Installed"
}

cleanup () {
	if [ -d /var/cache/c9-core-installer/ ] ; then
		rm -rf /var/cache/c9-core-installer/ || true
	fi
}

case "$1" in
    configure)
	npm_install
	c9_directory
	cleanup
    ;;

    abort-upgrade|abort-remove|abort-deconfigure)
    ;;

    *)
        echo "postinst called with unknown argument \`$1'" >&2
        exit 1
    ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0

